<template>
  <el-config-provider :locale="appStore.locale" :size="(appStore.size as any)">
    <div class="p-5">
      <!-- 查询条件 -->
      <div class="query-condition flex justify-between">
        <div class="condition">
          <el-input class="w-50 mr-3" v-model="searchInfo.menuName" placeholder="菜单名"></el-input>
          <el-button type="primary" plain @click="(searchInfo.menuName = ''), loadSyncMenu()">
            <i-ep-Refresh />
          </el-button>
          <el-button type="primary" @click="loadSyncMenu">
            <i-ep-Search />
          </el-button>
        </div>
      </div>

      <!-- 表格展示 -->
      <div class="table-content mt-5">
        <el-table :data="tableData" border :cell-style="cellStyle" style="width: 100%">
          <el-table-column align="center" type="index" width="60" label="序号"></el-table-column>
          <el-table-column align="center" prop="menuName" label="菜单名称"></el-table-column>
          <el-table-column align="center" prop="authType" label="权限类型"></el-table-column>
          <el-table-column align="center" prop="authContent" label="指定内容"></el-table-column>
          <el-table-column align="center" label="操作" width="80">
            <template #default="{ row }">
              <el-button plain type="primary" size="small" @click="editItem(row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="mt-4">
        <el-pagination
          v-model:current-page="searchInfo.page"
          v-model:page-size="searchInfo.limit"
          background
          layout="prev, pager, next, jumper, total"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 编辑权限 -->
    <el-dialog title="编辑权限" width="800" v-model="showDialog" :close-on-click-modal="false">
      <div class="flex flex-col">
        <el-form v-loading="loadingField" label-width="100px" label-position="left">
          <el-form-item label="权限类型">
            <el-radio-group v-model="dataForm.authType">
              <el-radio label="不指定条件"></el-radio>
              <el-radio label="指定部门可见数据"></el-radio>
              <el-radio label="指定人可见数据"></el-radio>
              <el-radio label="指定字段参数可见数据"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择部门" v-if="dataForm.authType === '指定部门可见数据'">
            <el-select
              class="w-80%"
              filterable
              multiple
              clearable
              v-model="dataForm.orgIds"
              placeholder="选择部门"
            >
              <el-option
                v-for="item in orgInfo"
                :key="item.orgId"
                :label="item.orgName"
                :value="item.orgId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择接收人" v-if="dataForm.authType === '指定人可见数据'">
            <el-select
              class="w-80%"
              filterable
              multiple
              clearable
              v-model="dataForm.users"
              placeholder="选择接收人"
            >
              <el-option
                v-for="item in userSelect"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="选择字段" v-if="dataForm.authType === '指定字段参数可见数据'">
            <div class="by-field flex flex-col">
              <div class="mb-3">
                <el-button @click="addCondition" type="primary">
                  <i-ep-CirclePlusFilled class="mr-1" />
                  新增条件
                </el-button>
              </div>
              <div
                class="mb-3 p-5 shadow bg-gray1"
                v-for="(item, index) in dataForm.fieldConditon"
                :key="index"
              >
                <div class="flex mb-5">
                  <el-select
                    @change="item.personDepGroup = []"
                    v-model="item.type"
                    class="w-100%"
                    placeholder="选择人员或者部门"
                  >
                    <el-option label="按人员" value="按人员"></el-option>
                    <el-option label="按部门" value="按部门"></el-option>
                  </el-select>
                  <el-select
                    multiple
                    filterable
                    clearable
                    collapse-tags
                    collapse-tags-tooltip
                    v-model="item.personDepGroup"
                    class="w-100% mx-3"
                    :placeholder="item.type === '按部门' ? '具体部门' : '具体人员'"
                  >
                    <div v-if="item.type === '按部门'">
                      <el-option
                        v-for="item in orgInfo"
                        :key="item.orgId"
                        :label="item.orgName"
                        :value="item.orgId"
                      ></el-option>
                    </div>
                    <div v-else>
                      <el-option
                        v-for="item in userSelect"
                        :key="item.userId"
                        :label="item.userName"
                        :value="item.userId"
                      ></el-option>
                    </div>
                  </el-select>
                  <el-button type="primary" @click="addField(item)" plain>
                    <i-ep-Plus class="mr-1" />
                    新增字段
                  </el-button>
                  <el-button
                    @click="dataForm.fieldConditon.splice(index, 1)"
                    class="mr-3"
                    type="danger"
                    plain
                  >
                    <i-ep-Delete class="mr-1" />
                    删除本条
                  </el-button>
                </div>

                <div class="flex mb-3 last:mb-0" v-for="(item__, index__) in item.fieldList">
                  <el-select
                    @change="toggleField(item__)"
                    v-model="item__.fieldId"
                    placeholder="选择字段"
                  >
                    <el-option
                      v-for="key in fieldSelect"
                      :key="key.fieldId"
                      :label="key.fieldName"
                      :value="key.fieldId"
                    ></el-option>
                  </el-select>
                  <span class="mx-3 color-gray6">=</span>
                  <el-tree-select
                    class="mr-3"
                    clearable
                    placeholder="选择字段选项"
                    v-model="item__.fieldCode"
                    @change="changeTreeSelect(item__)"
                    :data="item__.itemSelect"
                    :render-after-expand="false"
                    node-key="selectCode"
                    :props="{
                      label: 'selectName',
                      children: 'children'
                    }"
                  >
                    <template #default="{ data: { selectName, selectCode } }">
                      {{ selectCode }} {{ selectName }}
                    </template>
                  </el-tree-select>
                  <el-button
                    :disabled="item.fieldList.length === 1"
                    type="danger"
                    link
                    @click="item.fieldList.splice(index__, 1)"
                  >
                    <i-ep-Delete />
                  </el-button>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="flex justify-end">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button :disabled="judeEnabled" @click="savePermission" :loading="loadingBtn" type="primary">
          保 存
        </el-button>
      </div>
    </el-dialog>
  </el-config-provider>
</template>

<script setup lang="ts">
//@ts-nocheck
import { useQueryTable } from '@/utils/hooks/useQueryTable';
import { useAppStore } from '@/store/modules/app';
import XyTools from '@/utils/functions/xy-tools';
import {
  ledgerMenuTabApi,
  ledgerMenuTableFieldListApi,
  userListApi,
  ledgerMenuFormApi,
  ledgerFieldSelectTabApi
} from '@/utils/api/dataPermission';
import config from '@/utils/config';
import axios from 'axios';
import { json } from 'stream/consumers';

const appStore = useAppStore();
const $xy = new XyTools();
const loadingField = ref(false);
const showDialog = ref(false);
const fieldSelect = ref([]);
const dataForm = ref({
  authType: '不指定条件',
  fieldConditon: [],
  authContent: '',
  orgIds: [],
  users: [],
  authJson: ''
});

let orgInfo = []; /* 组织信息 */
let userSelect = []; /* 用户下拉 */

// 初始化
const init = async () => {
  loadSyncMenu();
  queryOrgInfo();
  getUserList();
};

// 获取用户列表
const getUserList = async () => {
  const res = await userListApi();

  if (res.status === 200) {
    userSelect = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 查询已经同步的菜单
const loadSyncMenu = async () => {
  loading.value = true;
  const res = await ledgerMenuTabApi(searchInfo);
  loading.value = false;

  if (res.status === 200) {
    tableData.value = res.data;
    total.value = res.count ? Number(res.count) : 0;
  } else {
    ElMessage.error(res.msg);
  }
};

// 切换树形下拉选项
const changeTreeSelect = (val) => {
  const treeVal = findNodeById(val.itemSelect, val.fieldCode);

  if (treeVal) {
    val.fieldVal = treeVal.selectName;
  }
};

// 查询树形结构node节点
const findNodeById = (tree, id) => {
  for (let node of tree) {
    if (node.selectCode === id) {
      return node;
    }

    if (node.children && node.children.length > 0) {
      const foundNode = findNodeById(node.children, id);
      if (foundNode) {
        return foundNode;
      }
    }
  }

  return null;
};

// 切换字段
const toggleField = async (val) => {
  val.fieldCode = '';

  const res = await ledgerFieldSelectTabApi({ page: 1, limit: 9999, fieldId: val.fieldId });

  if (res.status === 200) {
    val.itemSelect = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

// 判断是否能够点击
const judeEnabled = computed(() => {
  let flag = false;

  if (dataForm.value.authType === '指定部门可见数据') {
    if (dataForm.value.orgIds.length === 0) flag = true;
  } else if (dataForm.value.authType === '指定人可见数据') {
    if (dataForm.value.users.length === 0) flag = true;
  } else if (dataForm.value.authType === '指定字段参数可见数据') {
    if (dataForm.value.fieldConditon.length === 0) flag = true;

    const obj = dataForm.value.fieldConditon.find((item) => item.personDepGroup.length === 0);

    if (obj) {
      flag = true;
    }

    dataForm.value.fieldConditon.forEach((item) => {
      const __obj = item.fieldList.find((key) => !key.fieldCode || !key.fieldId);

      if (__obj) {
        flag = true;
      }
    });
  }

  return flag;
});

// 新增条件
const addCondition = () => {
  dataForm.value.fieldConditon.push({
    id: $xy.RI(),
    type: '按人员',
    personDepGroup: [],
    fieldList: [
      {
        fieldId: '',
        fieldVal: '',
        fieldCode: ''
      }
    ]
  });
};

// 添加字段
const addField = (row) => {
  row.fieldList.push({
    fieldId: '',
    fieldVal: '',
    fieldCode: ''
  });
};

// 查询组织信息
const queryOrgInfo = async () => {
  const res = await axios.get(config.baseUrl + '/cdledger/ledger-menu-do/organList', {
    headers: { token: config.token }
  });

  if (res.data && res.data.status && res.data.status === 200) {
    orgInfo = res.data.data;
  } else {
    ElMessage.error(res.data.status.message);
  }
};

// 读取对应的字段信息
const loadFieldList = async (id: string) => {
  loadingField.value = true;
  const res = await ledgerMenuTableFieldListApi({ id });
  loadingField.value = false;

  if (res.status === 200) {
    if (res.data && res.data.length > 0) {
      fieldSelect.value = res.data.filter((item) => {
        return item.fieldType === '复选框' || item.fieldType === '单选框' || item.fieldType === '下拉框';
      });
    }
  } else {
    ElMessage.error(res.msg);
  }
};

// 保存权限
const savePermission = async () => {
  loadingBtn.value = true;

  if (dataForm.value.authType === '指定部门可见数据') {
    let arr = [];

    dataForm.value.orgIds.forEach((item) => {
      const obj = orgInfo.find((key) => key.orgId === item);

      if (obj) {
        arr.push(obj.orgName);
      }
    });

    dataForm.value.authContent = arr.join(',');
    dataForm.value.authJson = JSON.stringify(dataForm.value.orgIds);
  } else if (dataForm.value.authType === '指定人可见数据') {
    let arr = [];

    dataForm.value.users.forEach((item) => {
      const obj = userSelect.find((key) => key.userId === item);

      if (obj) {
        arr.push(obj.userName);
      }
    });

    dataForm.value.authContent = arr.join(',');
    dataForm.value.authJson = JSON.stringify(dataForm.value.users);
  } else if (dataForm.value.authType === '指定字段参数可见数据') {
    dataForm.value.authContent = dataForm.value.fieldConditon[0].fieldList
      .map((item) => {
        const obj = fieldSelect.value.find((key) => key.fieldId === item.fieldId);

        if (obj) return obj.fieldName;
      })
      .join(',');

    dataForm.value.authJson = JSON.stringify(dataForm.value.fieldConditon);
  } else {
    dataForm.value.authContent = '';
    dataForm.value.authJson = '';
  }

  const res = await ledgerMenuFormApi(toRaw(dataForm.value));

  loadingBtn.value = false;

  if (res.status === 200) {
    loadSyncMenu();
    ElMessage.success('操作成功');
    showDialog.value = false;
  } else {
    ElMessage.error(res.msg);
  }
};

const {
  tableData,
  searchInfo,
  total,
  loading,
  loadingBtn,
  handleSizeChange,
  handleCurrentChange,
  cellStyle
} = useQueryTable(loadSyncMenu);

// 编辑权限
const editItem = (row) => {
  dataForm.value = JSON.parse(JSON.stringify(row));

  dataForm.value.authType = row.authType === '-' ? '不指定条件' : row.authType;
  dataForm.value.fieldConditon = [];
  dataForm.value.orgIds = [];
  dataForm.value.users = [];
  dataForm.value.authJson = '';
  dataForm.value.authContent = '';

  if (row.authType === '指定部门可见数据') {
    if (row.authJson) {
      dataForm.value.orgIds = JSON.parse(row.authJson);
    }
  } else if (row.authType === '指定人可见数据') {
    if (row.authJson) {
      dataForm.value.users = JSON.parse(row.authJson);
    }
  } else {
    dataForm.value.fieldConditon = row.authJson ? JSON.parse(row.authJson) : [];
  }

  showDialog.value = true;

  loadingBtn.value = false;

  loadFieldList(row.id);
};

init();
</script>

<style lang="scss" scoped></style>
